import { IContextMenu } from '@amcax/base';
import {
  Item,
  ItemParams,
  Menu,
  PredicateParams,
  Separator,
} from 'react-contexify';
import { wsApi } from '../../../../server/wsApi';
import { docMgr } from '../../../../manager/DocumentManager';

let params: any;

function ContextMenu(props: any) {
  function isItemHidden({
    triggerEvent,
    props,
    data,
  }: PredicateParams<any, any>): boolean {
    const visibility = props.visibility;
    return visibility === data;
  }
  function handleItemClick({
    id,
    triggerEvent,
    event,
    props,
    data,
  }: ItemParams<any, any>) {
    console.log('handleItemClick', id, triggerEvent, event, props, data);
    if (id === 'hide') {
      setModelVisibility(props.dxid, false);
    } else if (id === 'show') {
      setModelVisibility(props.dxid, true);
    } else if (id === 'delete') {
      deleteModel(props.dxid);
    }
  }
  const setModelVisibility = (dxid: string, visibility: boolean) => {
    console.log('setModelVisibility', dxid, visibility);
    wsApi.setVisible(dxid, visibility);
    docMgr.updateDocumentObjects();
  };
  const deleteModel = (dxid: string) => {
    wsApi.delete(dxid);
    docMgr.updateDocumentObjects();
  };

  return (
    <Menu id={props.id}>
      <Item
        id='hide'
        onClick={handleItemClick}
        hidden={isItemHidden}
        data={false}>
        隐藏
      </Item>
      <Item
        id='show'
        onClick={handleItemClick}
        hidden={isItemHidden}
        data={true}>
        显示
      </Item>
      <Separator />
      <Item
        id='delete'
        onClick={handleItemClick}>
        删除
      </Item>
    </Menu>
  );
}

const setParams = (_params: any) => {
  params = _params;
};

export const TreeContextMenu: IContextMenu = {
  id: 'treeContextMenu',
  render: (id: string) => <ContextMenu id={id} />,
};
